import { Auth } from '@/decorator/auth.decorator';
import { PrismaService } from '@/prisma/prisma.service';
import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  BadRequestException,
  Req,
  Put,
} from '@nestjs/common';
import { PrismaClient, user } from '@prisma/client';
import { AuthService } from './auth.service';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';
import { Request } from 'express';
@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private prisma: PrismaService,
  ) {}

  @Post()
  async create(@Body() createAuthDto: CreateAuthDto) {
    // 查询数据中是否有该用户 t 返回该用户的token 创建用户
    const openid = await this.authService.getWxOpenId(createAuthDto.code);
    if (!Boolean(openid)) {
      throw new BadRequestException('code有误');
    }
    const result: any = await this.authService.isExist(
      'user',
      'openid',
      openid,
    );
    if (result) {
      return this.authService.token(result);
    } else {
      return this.authService.create(openid);
    }
    // console.log('result', result);
    // return this.authService.create(openId);
  }

  @Get()
  @Auth()
  /**
   * 查询用户信息
   */
  findUseinfo(@Req() req: Request) {
    return this.authService.findUseinfo(req);
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.authService.findOne(+id);
  }
  /**
   * 更新用户信息
   */
  @Put()
  @Auth()
  update(@Body() updateAuthDto: UpdateAuthDto, @Req() req) {
    return this.authService.update(updateAuthDto, req);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.authService.remove(+id);
  }
}
